<template>
	<view class="index ">
		<!--简洁 -->
		<view class="f-1 bff1 box" style="margin: 10px;">
			<u--form labelPosition="left" :model="form" :rules="rules" ref="uForm">
				<u-form-item label="点单品名称:" prop="name" ref="item1" labelWidth="100px" :required="true" borderBottom>
					<u--input placeholder="请输入点单品名称" border="none" v-model="form.name" placeholderClass="init"
						:customStyle="{padding:' 15px 10px ',background:'#fff',borderRadius:'16rpx'}"></u--input>
				</u-form-item>
				<u-form-item label="时间:" ref="item1" labelWidth="40px" :required="true" borderBottom>
					<mg-cell isr='1' ht="" class="zanwei">
						<view slot='bd' class="f-y-c">
							<view @click="toggleTab('time1')" class="f-1 t-c" style="width: 280rpx;text-align: right;">
								{{form.start_time||'开始日期'}}
							</view>
							<view> 至 </view>
							<view @click="toggleTab('time2')" class="f-1 t-c" style="width: 300rpx;">
								{{form.end_time||'结束日期'}}
							</view>
						</view>
					</mg-cell>
				</u-form-item>
				<u-form-item label="图片:" ref="item1" labelWidth="40px" :required="true" borderBottom>
					<u-upload :fileList="form.img" @afterRead="afterRead" @delete="deletePic" uploadIcon="plus"
						style="margin-top: 15rpx;" name="1" :maxCount="1"></u-upload>
				</u-form-item>
				<category ref="categoryRef"></category>
				<view class="title">适用门店</view>
				<u-form-item label="" prop="pois" ref="item1" labelWidth="0" borderBottom>
					<scroll-view class="scroll f-1 bf8 db" scroll-y="true">
						<view>
							<checkbox-group class="uni-list" @change="checkboxChange">
								<label class="uni-list-cell uni-list-cell-pd flex mt10" v-for="item in menlist"
									:key="item.dy_poi_id">
									<view class="flex" style="align-items: center;">
										<view>
											<checkbox :value="item.dy_poi_id" :checked="item.checked"></checkbox>
										</view>
										<view class="flex" style="align-items: center;">
											{{item.store_name}}
										</view>
									</view>
									<view>
										<u--input placeholder="请输入库存" border="none" type="number" v-model="item.stock"
											placeholderClass="init"
											:customStyle="{padding:' 8px 6px ',background:'#f5f5f5',borderRadius:'16rpx'}"></u--input>
									</view>
								</label>
							</checkbox-group>
						</view>
					</scroll-view>
				</u-form-item>
				<view class="title">加料品</view>
				<u-form-item label="" prop="add_food_id" ref="item1" labelWidth="0" borderBottom>
					<scroll-view class="scroll f-1 bf8 db" scroll-y="true">
						<view>
							<u-radio-group v-model="form.add_food_id" @change="JialiaoChange">
								<u-radio v-for="(item, index) in jialiaolist" :key="index" :name="item.id">
									{{item.name}}
								</u-radio>
							</u-radio-group>
						</view>
					</scroll-view>
				</u-form-item>
				<view class="title">SPU标品</view>
				<u-form-item label="" prop="spu_id" ref="item1" labelWidth="0" borderBottom>
					<scroll-view class="scroll f-1 bf8 db" scroll-y="true">
						<view>
							<u-radio-group v-model="form.spu_id" @change="checkboxSpuChange">
								<u-radio v-for="(item, index) in spulist" :key="index" :name="item.id">
									{{item.name}}
								</u-radio>
							</u-radio-group>
						</view>
					</scroll-view>
				</u-form-item>
				<view v-if="form.sku_list.length>0" class="title">规格信息</view>
				<scroll-view class="scroll f-1 bf8 db" scroll-y="true" v-if="form.sku_list.length>0">
					<view v-for="(item,i) in form.sku_list" :key="i">
						<view class="flex">
							<u-tag mode="light" :text="item.name" type="primary" plain />
						</view>
						<view class="flex">
							<view class=" juzong">
								商品总价(元)：
								<u--input placeholder="请输入商品总价" border="none" type="number" v-model="item.origin_amount"
									placeholderClass="init"
									:customStyle="{padding:' 15px 10px ',background:'#fff',borderRadius:'16rpx'}"></u--input>
							</view>
							<view class=" juzong">
								团购价(元)：
								<u--input placeholder="请输入团购价" border="none" type="number" v-model="item.actual_amount"
									placeholderClass="init"
									:customStyle="{padding:' 15px 10px ',background:'#fff',borderRadius:'16rpx'}"></u--input>
							</view>
						</view>

						<u-divider></u-divider>
					</view>

				</scroll-view>
			</u--form>
		</view>


		<w-picker mode="dateTime" :defaultVal="nowDate" :current="false" :hasSecond="false"
			@confirm="onConfirm($event,'time1')" ref="time1" step="1"></w-picker>
		<w-picker mode="dateTime" :defaultVal="nowDate" :current="false" :hasSecond="false"
			@confirm="onConfirm($event,'time2')" ref="time2" step="1"></w-picker>

		<!-- 按钮 -->
		<view class="mt10 guding">
			<u-button type="primary" :loading="loading" :customStyle="{color:'#000'}" :plain="true" text="确定"
				color="#0055ff" @click="submit()">
			</u-button>
		</view>
	</view>
</template>

<script>
	import mgCell from '@/components/common/mg-cell.vue'
	import wPicker from "@/components/form/w-picker.vue";
	import category from "@/components/category/category.vue";
	import config from '@/custom/config.js';
	import site from '@/custom/siteroot.js';
	export default {
		components: {
			mgCell,
			wPicker,
			category
		},
		data() {
			return {
				form: {
					name: '',
					category_one_id: '',
					category_two_id: '',
					category_three_id: '',
					start_time: '',
					end_time: '',
					img: [],
					pois: [],
					add_food_id: '',
					add_ids: [],
					attr_ids: [],
					spu_id: '',
					sku_list: []
				},
				menlist: [],
				jialiaolist: [],
				spulist: [],
				nowDate: '',
				rules: {
					name: [{
						required: true,
						message: '请输入点单品名称',
						trigger: ['blur'],
					}, ],
				},
				addAndEditType: 0,
				info_id: '',
				loading: false,
				hexList: []
			}
		},
		onLoad(option) {
			this.nowDate = this.formatTime(new Date().getTime());
			if (option.id) {
				this.info_id = option.id;

			}
			for (let i = 0; i <= 15; i++) {
				this.hexList[i] = i.toString(16)
			}
			this.getjialioapinList();
			this.getspupinList();
			this.getSYMenList();
		},
		watch: {

		},
		methods: {
			async getspupinList() {
				let {
					data: {
						data
					}
				} = await this.beg.request({
					url: '/admin/product.Spu/index',
					method: 'POST',
					data: {
						operate_status: 1,
						is_deleted: 0
					},
				})
				data.forEach((val) => {
					val.checked = false;
				})
				this.spulist = data;

			},
			async getSYMenList() {
				let {
					data
				} = await this.beg.request({
					url: '/admin/product.AddFood/getStore',
					method: 'POST',
					data: {
						province: '',
					},
				})
				data.forEach((val) => {
					val.stock = 100;
					val.checked = false;
				})
				this.menlist = data;
				if (this.info_id != '') {
					this.getInfo();
				}

			},
			formatTime(date) {
				let newDate = new Date(date);
				const year = newDate.getFullYear();
				const month = ('0' + (newDate.getMonth() + 1)).slice(-2); // 月份是从0开始的，所以需要加1  
				const day = ('0' + newDate.getDate()).slice(-2);
				const hours = ('0' + newDate.getHours()).slice(-2);
				const minutes = ('0' + newDate.getMinutes()).slice(-2);
				const seconds = ('0' + newDate.getSeconds()).slice(-2);
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			toggleTab(str) {
				this.$refs[str].show();
			},
			onConfirm(e, key) {
				console.log(e, key);
				switch (key) {
					case "time1":
						this.form.start_time = e.result
						break;
					case "time2":
						this.form.end_time = e.result
						break;
				}
			},
			async getInfo() {
				let {
					code,
					data,
					msg
				} = await this.beg.request({
					url: '/admin/product.Place/getInfo',
					method: 'POST',
					data: {
						id: this.info_id,
					},
				})
				if (code == 1) {
					let pois = [];
					data.pois.forEach((v) => {
						this.menlist.forEach((vv) => {
							vv.stock = 100;
							vv.checked = false;
							if (vv.dy_poi_id == v.poi_id) {
								let obj = {
									poi_id: v.poi_id,
									stock: v.stock,
								}
								vv.stock = v.stock;
								pois.push(obj);
								vv.checked = true;
							}
						})
					})
					let img = [];
					img.push({
						url: site.siteroot + data.img,
						src: data.img
					});
					data.img = img;
					console.log(data)
					data.pois = pois;
					console.log(pois)
					data.sku_list.forEach((v) => {
						v.actual_amount = Number(v.actual_amount) / 100;
						v.origin_amount = Number(v.origin_amount) / 100;
					})
					Object.assign(this.form, data);
					this.$refs.categoryRef.category_one_id = this.form.category_one_id;
					this.$refs.categoryRef.category_two_id = this.form.category_two_id;
					this.$refs.categoryRef.category_three_id = this.form.category_three_id;

					this.$refs.categoryRef.getcategory(this.form.category_one_id, 2);
					this.$refs.categoryRef.getcategory(this.form.category_two_id, 3);
					// this.getcategory(this.form.category_one_id, 2);
					// this.getcategory(this.form.category_two_id, 3);

				} else {
					uni.$u.toast(msg)
				}
			},
			checkboxChange(e) {
				let pois = [];
				this.menlist.forEach((v) => {
					e.detail.value.forEach((vv) => {
						if (v.dy_poi_id == vv) {
							let obj = {};
							obj.poi_id = v.dy_poi_id;
							obj.stock = v.stock;
							pois.push(obj);
						}
					})
				})
				this.form.pois = pois;
			},
			JialiaoChange(e) {
				this.jialiaolist.forEach((v) => {
					if (e == v.id) {
						this.form.add_food_id = v.id;
						this.form.add_ids = v.add_ids;
					}
				})
			},
			checkboxSpuChange(e) {
				let spuid = 0;
				this.spulist.forEach((v) => {
					if (v.id == e) {
						spuid = e;
						this.form.attr_ids = v.attr_ids;
					}
				})
				this.getGuigeList(spuid);
			},
			async getGuigeList(spuid) {
				let {
					code,
					data,
					msg
				} = await this.beg.request({
					url: '/admin/product.Spu/getInfo',
					method: 'POST',
					data: {
						id: spuid,
					},
				})
				if (code == 1) {
					data.sku_list.forEach((v) => {
						v.origin_amount = 0;
						v.actual_amount = 0;
						v.attr_list = v.attr_list_child;
					});
					this.form.sku_list = data.sku_list;
				} else {
					uni.$u.toast(msg)
				}
			},
			async getjialioapinList() {
				let {
					data: {
						data
					}
				} = await this.beg.request({
					url: '/admin/product.AddFood/addClassIndex',
					method: 'POST',
					data: {
						page: 1,
						limit: 200,
						is_deleted: 0
					},
				})
				data.forEach((val) => {
					val.checked = false;
				})
				this.jialiaolist = data;

			},
			submit() {
				this.form.category_one_id = this.$refs.categoryRef.category_one_id;
				this.form.category_two_id = this.$refs.categoryRef.category_two_id;
				this.form.category_three_id = this.$refs.categoryRef.category_three_id;

				if (this.form.start_time == '') {
					uni.$u.toast('请选择开始时间')
					return;
				}
				if (this.form.end_time == '') {
					uni.$u.toast('请选择开始时间')
					return;
				}
				if (new Date(this.form.start_time).getTime() > new Date(this.form.end_time).getTime()) {
					uni.$u.toast('开始时间不能大于结束时间')
					return;
				}
				if (this.form.img.length == 0) {
					uni.$u.toast('请上传图片')
					return;
				}
				if (this.form.category_three_id == '') {
					uni.$u.toast('请检查品类是否正确')
					return;
				}
				if (this.form.pois.length == 0) {
					uni.$u.toast('请选择适用门店')
					return;
				}
				if (this.form.add_food_id == '') {
					uni.$u.toast('请选择加料品')
					return;
				}
				if (this.form.spu_id == '') {
					uni.$u.toast('请选择SPU标品')
					return;
				}
				//检查规格
				let status = false;
				this.form.sku_list.forEach((v) => {
					if (v.origin_amount == 0) {
						status = true;
						return;
					}
					if (v.actual_amount == 0) {
						status = true;
						return;
					}
					if (v.actual_amount > v.origin_amount) {
						status = true;
						return;
					}
				})
				if (status) {
					uni.$u.toast('请选择规格是否正确（不能出现0或者团购价大于商品总价）')
				}

				this.$refs.uForm.validate().then(res => {
					let data = {};
					let obj = {
						...this.form
					}
					data = {
						...data,
						...obj
					}
					let sku_list = [...obj.sku_list];
					sku_list.forEach((v) => {
						v.origin_amount = Number(v.origin_amount) * 100;
						v.actual_amount = Number(v.actual_amount) * 100;
					})
					data.sku_list = sku_list;
					let pois = [];
					this.menlist.forEach((v) => {
						this.form.pois.forEach((vv) => {
							if (v.dy_poi_id == vv.poi_id) {
								let obj = {};
								obj.local_store_id = v.id;
								obj.poi_id = vv.poi_id;
								obj.stock = vv.stock;
								pois.push(obj);
							}
						})
					})
					data.pois = pois;
					data.img = data.img[0].src;
					this.postData(data);
				}).catch(errors => {
					uni.$u.toast('请填写完整的信息')
				})
			},
			async postData(data) {
				this.loading = true;
				let {
					code,
					msg
				} = await this.beg.request({
					url: '/admin/product.Place/save',
					method: 'POST',
					data: data,
				})
				if (code == 1) {
					uni.$u.toast(msg);
					setTimeout(() => {
						this.returnIndex();
					}, 1000)
				} else {
					this.loading = false;
					uni.$u.toast(msg)
				}
				this.loading = false;
			},
			//返回
			returnIndex() {
				this.loading = false;
				uni.navigateBack({
					delta: 1
				});
			},
			deletePic(event) {
				this.form.img.splice(event.index, 1)
			},
			async afterRead(event) {
				let lists = [].concat(event.file)
				let fileListLen = this.form.img.length
				lists.map((item) => {
					this.form.img.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.form.img[fileListLen]
					console.log(item)
					console.log(fileListLen)
					this.form.img.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: site.siteroot + result.file.url,
						src: result.file.url,
						file: result.file
					}))
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let adminInfo = uni.getStorageSync('adminInfo');
					let a = uni.uploadFile({
						url: site.siteroot + `/admin/ajax/upload?uuid=` + this.uuid(),
						filePath: url,
						name: 'file',
						header: {
							Accept: "application/json, text/plain, */*",
							contentType: config.contentType,
							agentId: adminInfo.agent_id,
							batoken: adminInfo.token,
							chainStoresId: adminInfo.chain_stores_id,
							oemId: adminInfo.oem_id,
							partnerId: adminInfo.partner_id,
							server: "true",
							storeId: adminInfo.store_id,
							thinkLang: "zh-cn",
						},
						success: (res) => {
							let r = JSON.parse(res.data)
							if (r && r.code == 1) {
								setTimeout(() => {
									let d = JSON.parse(res.data);
									resolve(d.data)
								}, 500)

							} else {
								uni.showToast({
									title: r.msg || r.code,
									icon: 'none',
									duration: 2000
								})
							}
						},
						fail: (res) => {
							return uni.$u.toast(res && res.data || res)
						}
					});
				})
			},
			/**
			 * 生成全球唯一标识
			 * @returns uuid
			 */
			uuid() {
				let uuid = ''
				for (let i = 1; i <= 36; i++) {
					if (i === 9 || i === 14 || i === 19 || i === 24) {
						uuid += '-'
					} else if (i === 15) {
						uuid += 4
					} else if (i === 20) {
						uuid += this.hexList[(Math.random() * 4) | 8]
					} else {
						uuid += this.hexList[(Math.random() * 16) | 0]
					}
				}
				return uuid
			},
		}
	}
</script>

<style lang="scss" scoped>
	.box {
		background-color: #fff;
		padding: 20rpx;
		line-height: 1.5;
		position: relative;
		margin-top: 20rpx;
		border-radius: 20rpx;



		.prid {
			font-weight: bold;
			font-size: 32rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.jiao {
				right: 10rpx;

				.jiaohang {
					display: flex;
					align-items: center;

					.rijianju {
						margin-right: 10rpx;
					}
				}
			}
		}

		.prod {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: 20rpx;
		}

		.prname {
			width: 80%;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-line-clamp: 2;
			-webkit-box-orient: vertical;
		}

		.price {
			width: 20%;
			text-align: right;
		}
	}

	.scroll {
		height: 50vh;
		background-color: #fff;
	}

	/deep/.u-form-item__body {
		padding: 0px;
	}

	.zanwei {
		height: 100rpx;
		display: flex;
		align-items: center;
	}

	/deep/.u-radio-group--row {
		display: flex;
		flex-direction: column;
		line-height: 2;
	}

	.juzong {
		align-items: center;
		margin-top: 10rpx;
	}

	.title {
		font-weight: bold;
		padding: 20rpx;
	}

	// .guding{
	// 	position: fixed;
	// 	bottom: 0rpx;
	// 	width: 100%;
	// 	padding: 20rpx;
	// }
</style>